package com.jiutong.meipengdai.utils;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import android.annotation.TargetApi;
import android.os.Build;

import com.orhanobut.logger.Logger;

/**
 * @Description:简单异步线程池
 * @author:zhangqian
 * @copyright © zbxz.com
 * @Date:2014-12-12
 */
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class AppThreadPool {

	public enum ENUM_Thread_Level {
		TL_common, TL_AtOnce
	}

	private final static int I_COMMON_POOL_NUM = 10;
	private final static int I_ACCOUNT_POOL_NUM = 5;
	private final static int MAX_POLL_COUNT = 100;
	private static final String TAG = "NewsThreadPool";
	// 普通线程
	public static ThreadPoolExecutor poolInstance_common;
	// 唯一线程
	public static ThreadPoolExecutor poolInstance_AtOnce = (ThreadPoolExecutor) Executors
			.newFixedThreadPool(1);

	private AppThreadPool() {

	}

	public static ThreadPoolExecutor getInstance(ENUM_Thread_Level e_t_l) {
		switch (e_t_l) {
		case TL_common:
			return getInst_CommonPool();
		case TL_AtOnce:
			return getInst_AtOncePool();
		default:
			return getInst_CommonPool();
		}

	}

	private static ThreadPoolExecutor getInst_CommonPool() {
		try {
			if (poolInstance_common == null || poolInstance_common.isShutdown()) {
				poolInstance_common = (ThreadPoolExecutor) Executors
						.newFixedThreadPool(I_COMMON_POOL_NUM);
				poolInstance_common.setKeepAliveTime(10, TimeUnit.SECONDS);
				poolInstance_common.allowCoreThreadTimeOut(true);
				poolInstance_common.setMaximumPoolSize(MAX_POLL_COUNT);
			}
		} catch (Exception e) {
			Logger.i(TAG, "thread error: " + e.toString());
		}
		return poolInstance_common;
	}

	private static ThreadPoolExecutor getInst_AtOncePool() {
		try {
			if (poolInstance_AtOnce == null || poolInstance_AtOnce.isShutdown()) {
				poolInstance_AtOnce = (ThreadPoolExecutor) Executors
						.newFixedThreadPool(I_ACCOUNT_POOL_NUM);
			} else if (poolInstance_AtOnce != null) {//
				poolInstance_AtOnce.shutdownNow();
				poolInstance_AtOnce = (ThreadPoolExecutor) Executors
						.newFixedThreadPool(I_ACCOUNT_POOL_NUM);
			} else {
				poolInstance_AtOnce = (ThreadPoolExecutor) Executors
						.newFixedThreadPool(I_ACCOUNT_POOL_NUM);
			}
			poolInstance_AtOnce.setMaximumPoolSize(MAX_POLL_COUNT);
		} catch (Exception e) {
			Logger.i(TAG, "thread error: " + e.toString());
		}
		return poolInstance_AtOnce;
	}

}
